package com.qyer.commons;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.qyer.commons.concurrent.assemblingline.AssemblingLineException;
import com.qyer.commons.concurrent.assemblingline.creator.InstanceCreator;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * User: Z J Wu Date: 2016/06/04 Time: 16:40 Package: com.qyer.commons.concurrent
 */
public class Context {

  @JsonProperty("info")
  protected ConcurrentHashMap<String, Object> infoMap;

  public Context() {
    infoMap = new ConcurrentHashMap<>(16);
  }

  public synchronized <T> T putValueIfNull(String key, InstanceCreator<T> creator,
                                           Object... params) throws AssemblingLineException {
    if (StringUtils.isEmpty(key)) {
      throw new AssemblingLineException("Key is empty.");
    }
    Object o = infoMap.get(key);
    if (o == null) {
      T t = creator.create(params);
      infoMap.put(key, t);
      return t;
    }
    return (T) o;
  }

  public ConcurrentHashMap<String, Object> getInfoMap() {
    return infoMap;
  }

  public void setInfoMap(ConcurrentHashMap<String, Object> infoMap) {
    this.infoMap = infoMap;
  }
}
